/*
 * File:    Cookie.java
 * Created: 18-Feb-2009
 * Version: $Id$
 *
 * COPYRIGHT (C) 2009, Bitgate Mobile, LLC.  All Rights Reserved.
 *
 * software@bitgatemobile.com
 */

package com.webplasm.render.tags.u;

import static com.bitgate.util.debug.Debug.debug;

import java.util.Arrays;
import java.util.List;

import com.bitgate.util.service.protocol.http.HttpClientContext;
import com.bitgate.util.service.protocol.http.store.CookieStore;
import com.webplasm.context.RenderContext;
import com.webplasm.render.engine.RenderException;
import com.webplasm.render.tags.TagInterface;
import com.webplasm.render.tags.WrappedNode;

/**
 * This tag is used to retrieve and set the contents of HTTP cookies to and from clients.  Webplasm doesn't have an actual
 * limit on the number of cookies that can be set, however, most browsers (at time of writing) only support up to 50 cookies.
 * 
 * @author kenji
 * @since Webplasm 1.0
 */
public class Cookie extends WrappedNode implements TagInterface {
	private static final String DESCRIPTION = "Sets and retrieves HTTP(s) cookies.";
	
	private static final String COOKIE_MODE_SET = "set";
	private static final String COOKIE_MODE_GET = "get";
	
	public String getNamespace() {
		return "u";
	}
	
	public List<String> getAttributes() {
		return Arrays.asList("name", "mode");
	}
	
	public List<String> getManagedNodes() {
		return null;
	}

	public String getDescription() {
		return DESCRIPTION;
	}

	@Override
	public StringBuffer render(RenderContext rContext) throws RenderException {
		HttpClientContext hcContext = rContext.getClientContext();
		
		if (elements.get("name") == null) {
			throw new RenderException("u:cookie requires a 'name' attribute to be set.");
		}
		
		String cookieName = elements.get("name");
		String cookieMode = elements.get("mode");
		CookieStore cStore = hcContext.getIncomingCookie(cookieName);
		
		if (cookieMode == null) {
			cookieMode = COOKIE_MODE_GET;
		}
		
		if (cookieMode.equalsIgnoreCase(COOKIE_MODE_GET)) {
			debug("Cookie name '" + cookieName + "': " + cStore);
		
			if (cStore != null) {
				return new StringBuffer(cStore.getValue());
			}
		} else if (cookieMode.equalsIgnoreCase(COOKIE_MODE_SET)) {
			StringBuffer setBuffer = super.render(rContext);
			
			debug("Cookie name '" + cookieName + "': Setting with value '" + setBuffer.toString() + "'");
			
			CookieStore newStore = new CookieStore(cookieName, setBuffer.toString());
			
			hcContext.setOutgoingCookie(cookieName, newStore);
		} else {
			throw new RenderException("u:cookie encountered an unknown mode '" + cookieMode + "'");
		}
		
		return new StringBuffer();
	}
}